import { useState, useEffect, useRef } from 'react'
import sloarToLunar from '@/utils/date/SolarToLunar'

// 自定义Hook，返回当前的时、分、秒
export const useRealTime = () => {
  const initNow = new Date()
  const initHours = String(initNow.getHours()).padStart(2, '0')
  const initMinus = String(initNow.getMinutes()).padStart(2, '0')
  const [hours, setHours] = useState<string>(initHours)
  const [minutes, setMinutes] = useState<string>(initMinus)
  // const [seconds, setSeconds] = useState<string>('');

  const timerId = useRef<ReturnType<typeof setInterval> | null>(null)

  const weeks = [
    { solar: '周一', lunar: '月曜日' },
    { solar: '周二', lunar: '火曜日' },
    { solar: '周三', lunar: '水曜日' },
    { solar: '周四', lunar: '木曜日' },
    { solar: '周五', lunar: '金曜日' },
    { solar: '周六', lunar: '土曜日' },
    { solar: '周日', lunar: '日曜日' }
  ]
  const year = new Date().getFullYear()
  const month = new Date().getMonth() + 1
  const day = new Date().getDate()
  const week = weeks[new Date().getDay() - 1]
  const { lunarYear, lunarMonth, lunarDay } = sloarToLunar(year, month, day)
  const amPm = initNow.getHours() >= 12 ? 'PM' : 'AM'

  useEffect(() => {
    // 设置定时器，并存储其ID
    timerId.current = setInterval(() => {
      const now = new Date()
      // 分别更新时、分、秒的状态
      setHours(String(now.getHours()).padStart(2, '0'))
      setMinutes(String(now.getMinutes()).padStart(2, '0'))
      // setSeconds(String(now.getSeconds()).padStart(2, '0'));
    }, 1000)

    // 清除定时器，防止内存泄漏
    return () => {
      if (timerId.current !== null) {
        clearInterval(timerId.current)
      }
    }
  }, []) // 空依赖数组，确保effect只在Hook挂载和卸载时运行

  return { year, month, day, week, hours, minutes, lunarYear, lunarMonth, lunarDay, amPm }
}
